<?php
  require_once "Gi_Session.php";
  require_once "Gi_Sql_Writer.php";
  class Gi_Auth {
    private static $_identity = null;
    private static $_storage = null;
    private $_table = null;
    private $_identity_col = null;
    private $_credential_col = null;
    private $_enc_type = null;
    private static $_instance = null;
    
    private function __construct () {
      self::$_storage = Gi_Session::get_instance();
    }
    
    private function __clone () {
    }
    
    public static function get_instance () {
      if (null === self::$_instance){
        self::$_instance = new self();
      }
      self::$_identity = self::$_storage->gi_auth_identity;
      return self::$_instance;
    }
    
    public function has_identity() {
      if (null !== self::$_identity) {
        return true;
      }
      return false;
    }
    
    public function get_identity (){
      return self::$_identity;
    }
    
    public function set_table($table){
      $this->_table = $table;
    }
    
    public function set_identity_col ($col) {
      $this->_identity_col = $col;
    }
    
    public function set_credential_col ($col) {
      $this->_credential_col = $col;
    }
    
    public function set_enc_type ($enc_type) {
      $this->_enc_type = strtolower($enc_type);
    }
    
    public function autenticate ($user, $pass) {
      if($this->_enc_type !== null) {
        switch ($this->_enc_type) {
          case "md5" : 
            $pass = md5($pass);
            break;
          case "sha1" :
            $pass = sha1($pass);
            break;
          case "crc32" :
            $pass = crc32($pass);
            break;
          default : throw new Exception("encriptacion no soportada") ;
        }
      }
      $sql = new Gi_Sql_Writer("SELECT","$this->_table","$this->_identity_col");
      $sql->add_where("$this->_identity_col = ? AND $this->_credential_col = ?"); 
      $adapter = Gi_Db::get_adapter();
      $adapter->stmt_execute($sql, array($user,$pass));
      $result = $adapter->stmt_fetch_assoc();
      if ($result) {
        self::$_identity = $result;
        self::$_storage->gi_auth_identity = $result;
        return true;
      }
      else
        return false;
    }
  }
